<template>
  <div class="channel-analysis-container">
    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" :inline="true" label-width="80px">
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item label="渠道类型">
          <el-select v-model="filterForm.channelType" placeholder="请选择渠道类型" clearable>
            <el-option label="线上渠道" value="online" />
            <el-option label="线下渠道" value="offline" />
            <el-option label="合作渠道" value="partner" />
            <el-option label="直销渠道" value="direct" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleFilter" :loading="loading">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 渠道概览 -->
    <el-row :gutter="20" class="overview-row">
      <el-col :span="6">
        <el-card class="overview-card">
          <div class="overview-item">
            <div class="overview-icon online">
              <el-icon><Monitor /></el-icon>
            </div>
            <div class="overview-content">
              <div class="overview-value">{{ overviewData.onlineCount }}</div>
              <div class="overview-label">线上渠道</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="overview-card">
          <div class="overview-item">
            <div class="overview-icon offline">
              <el-icon><Shop /></el-icon>
            </div>
            <div class="overview-content">
              <div class="overview-value">{{ overviewData.offlineCount }}</div>
              <div class="overview-label">线下渠道</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="overview-card">
          <div class="overview-item">
            <div class="overview-icon partner">
              <el-icon><Connection /></el-icon>
            </div>
            <div class="overview-content">
              <div class="overview-value">{{ overviewData.partnerCount }}</div>
              <div class="overview-label">合作渠道</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="overview-card">
          <div class="overview-item">
            <div class="overview-icon direct">
              <el-icon><User /></el-icon>
            </div>
            <div class="overview-content">
              <div class="overview-value">{{ overviewData.directCount }}</div>
              <div class="overview-label">直销渠道</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表分析 -->
    <el-row :gutter="20" class="chart-row">
      <!-- 渠道成交金额分布 -->
      <el-col :span="12">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>渠道成交金额分布</span>
              <el-radio-group v-model="amountChartType" size="small">
                <el-radio-button label="pie">饼图</el-radio-button>
                <el-radio-button label="bar">柱状图</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="amountChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <!-- 渠道成交趋势 -->
      <el-col :span="12">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <span>渠道成交趋势</span>
          </template>
          <div ref="trendChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 渠道详细数据 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>渠道详细分析</span>
          <el-button type="success" size="small" @click="handleExport">
            <el-icon><Download /></el-icon>
            导出报表
          </el-button>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        style="width: 100%"
        :default-sort="{ prop: 'amount', order: 'descending' }"
      >
        <el-table-column prop="channelName" label="渠道名称" width="150" />
        <el-table-column prop="channelType" label="渠道类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getChannelTypeTag(row.channelType)">
              {{ getChannelTypeName(row.channelType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="customerCount" label="客户数量" width="100" align="center" />
        <el-table-column prop="dealCount" label="成交笔数" width="100" align="center" />
        <el-table-column prop="amount" label="成交金额（万元）" width="140" align="right" sortable>
          <template #default="{ row }">
            <span class="amount-text">{{ formatNumber(row.amount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="commission" label="佣金（万元）" width="120" align="right" sortable>
          <template #default="{ row }">
            <span class="commission-text">{{ formatNumber(row.commission) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="conversionRate" label="转化率" width="100" align="center">
          <template #default="{ row }">
            <span :class="getConversionRateClass(row.conversionRate)">
              {{ (row.conversionRate * 100).toFixed(1) }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="avgAmount" label="平均成交金额" width="140" align="right">
          <template #default="{ row }">
            {{ formatNumber(row.avgAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="manager" label="负责人" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleViewDetail(row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Download, Monitor, Shop, Connection, User } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 响应式数据
const loading = ref(false)
const amountChartRef = ref<HTMLDivElement>()
const trendChartRef = ref<HTMLDivElement>()
const amountChartType = ref('pie')

// 筛选表单
const filterForm = reactive({
  dateRange: [],
  channelType: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 概览数据
const overviewData = reactive({
  onlineCount: 0,
  offlineCount: 0,
  partnerCount: 0,
  directCount: 0
})

// 表格数据
const tableData = ref([])

// 图表实例
let amountChart: echarts.ECharts | null = null
let trendChart: echarts.ECharts | null = null

// 方法
const handleFilter = () => {
  pagination.page = 1
  getTableData()
  updateCharts()
}

const handleReset = () => {
  Object.assign(filterForm, {
    dateRange: [],
    channelType: ''
  })
  handleFilter()
}

const handleExport = () => {
  ElMessage.success('导出功能开发中')
}

const handleViewDetail = (row: any) => {
  ElMessage.info(`查看 ${row.channelName} 的详细信息`)
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  getTableData()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  getTableData()
}

const getTableData = async () => {
  loading.value = true
  try {
    // TODO: 调用API获取数据
    setTimeout(() => {
      tableData.value = [
        {
          channelName: '官方网站',
          channelType: 'online',
          customerCount: 1250,
          dealCount: 85,
          amount: 425.6,
          commission: 12.8,
          conversionRate: 0.068,
          avgAmount: 5.01,
          manager: '张三',
          status: 'active'
        },
        {
          channelName: '门店直销',
          channelType: 'offline',
          customerCount: 980,
          dealCount: 120,
          amount: 680.2,
          commission: 20.4,
          conversionRate: 0.122,
          avgAmount: 5.67,
          manager: '李四',
          status: 'active'
        }
      ]
      pagination.total = 50
      loading.value = false
    }, 1000)
  } catch (error) {
    loading.value = false
    ElMessage.error('获取数据失败')
  }
}

const initCharts = () => {
  nextTick(() => {
    if (amountChartRef.value) {
      amountChart = echarts.init(amountChartRef.value)
    }
    if (trendChartRef.value) {
      trendChart = echarts.init(trendChartRef.value)
    }
    updateCharts()
  })
}

const updateCharts = () => {
  updateAmountChart()
  updateTrendChart()
}

const updateAmountChart = () => {
  if (!amountChart) return
  
  const data = [
    { name: '线上渠道', value: 425.6 },
    { name: '线下渠道', value: 680.2 },
    { name: '合作渠道', value: 320.8 },
    { name: '直销渠道', value: 180.5 }
  ]
  
  if (amountChartType.value === 'pie') {
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c}万元 ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '成交金额',
          type: 'pie',
          radius: '50%',
          data: data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    amountChart.setOption(option)
  } else {
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      xAxis: {
        type: 'category',
        data: data.map(item => item.name)
      },
      yAxis: {
        type: 'value',
        name: '金额（万元）'
      },
      series: [
        {
          name: '成交金额',
          type: 'bar',
          data: data.map(item => item.value),
          itemStyle: {
            color: '#409eff'
          }
        }
      ]
    }
    amountChart.setOption(option)
  }
}

const updateTrendChart = () => {
  if (!trendChart) return
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['线上渠道', '线下渠道', '合作渠道', '直销渠道']
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value',
      name: '成交金额（万元）'
    },
    series: [
      {
        name: '线上渠道',
        type: 'line',
        data: [120, 132, 101, 134, 90, 230]
      },
      {
        name: '线下渠道',
        type: 'line',
        data: [220, 182, 191, 234, 290, 330]
      },
      {
        name: '合作渠道',
        type: 'line',
        data: [150, 232, 201, 154, 190, 330]
      },
      {
        name: '直销渠道',
        type: 'line',
        data: [98, 87, 106, 112, 133, 180]
      }
    ]
  }
  trendChart.setOption(option)
}

// 工具方法
const formatNumber = (num: number) => {
  return num?.toFixed(2) || '0.00'
}

const getChannelTypeTag = (type: string) => {
  const tagMap: Record<string, string> = {
    online: 'primary',
    offline: 'success',
    partner: 'warning',
    direct: 'info'
  }
  return tagMap[type] || 'info'
}

const getChannelTypeName = (type: string) => {
  const nameMap: Record<string, string> = {
    online: '线上渠道',
    offline: '线下渠道',
    partner: '合作渠道',
    direct: '直销渠道'
  }
  return nameMap[type] || type
}

const getStatusTag = (status: string) => {
  const tagMap: Record<string, string> = {
    active: 'success',
    inactive: 'danger',
    pending: 'warning'
  }
  return tagMap[status] || 'info'
}

const getStatusName = (status: string) => {
  const nameMap: Record<string, string> = {
    active: '活跃',
    inactive: '停用',
    pending: '待审核'
  }
  return nameMap[status] || status
}

const getConversionRateClass = (rate: number) => {
  if (rate >= 0.1) return 'high-rate'
  if (rate >= 0.05) return 'medium-rate'
  return 'low-rate'
}

// 初始化数据
const initData = () => {
  Object.assign(overviewData, {
    onlineCount: 15,
    offlineCount: 8,
    partnerCount: 12,
    directCount: 6
  })
  
  getTableData()
  initCharts()
}

// 监听图表类型变化
watch(() => amountChartType.value, () => {
  updateAmountChart()
})

onMounted(() => {
  initData()
})
</script>

<style lang="scss" scoped>
.channel-analysis-container {
  padding: 20px;
  
  .filter-card {
    margin-bottom: 20px;
  }
  
  .overview-row {
    margin-bottom: 20px;
    
    .overview-card {
      .overview-item {
        display: flex;
        align-items: center;
        
        .overview-icon {
          width: 60px;
          height: 60px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 15px;
          font-size: 24px;
          color: white;
          
          &.online {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          }
          
          &.offline {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
          }
          
          &.partner {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
          }
          
          &.direct {
            background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
          }
        }
        
        .overview-content {
          .overview-value {
            font-size: 24px;
            font-weight: bold;
            color: #303133;
            margin-bottom: 5px;
          }
          
          .overview-label {
            font-size: 14px;
            color: #909399;
          }
        }
      }
    }
  }
  
  .chart-row {
    margin-bottom: 20px;
    
    .chart-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      
      .chart-container {
        height: 300px;
      }
    }
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .amount-text {
      color: #67c23a;
      font-weight: bold;
    }
    
    .commission-text {
      color: #e6a23c;
      font-weight: bold;
    }
    
    .high-rate {
      color: #67c23a;
      font-weight: bold;
    }
    
    .medium-rate {
      color: #e6a23c;
      font-weight: bold;
    }
    
    .low-rate {
      color: #f56c6c;
      font-weight: bold;
    }
    
    .pagination-container {
      margin-top: 20px;
      text-align: right;
    }
  }
}
</style>
